<?php
/*
 * @Description:
 * @Author: Leequik
 * @Date: 2025-03-19 22:50:47
 * @LastEditTime: 2025-06-04 11:45:14
 * @LastEditors: Leequik
 */

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Redis;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;


class TestController extends Controller
{
    public function index()
    {
        return view('test/index');
        
    }

    //获取当前redis中前20的key
    public function get_keys(){
        
        $redis = app('redis');
        /*
        $iterator = null;
        $keys = [];

        while (true) {
            $result = $redis->scan($iterator, ['count' => 20]); // 每次扫描返回最多20个键
            $keys = array_merge($keys, $result[1]);

            if ($iterator === 0) {
                break;
            }
        }

        // 取前20个键
        $keys = array_slice($keys, 0, 20);
        */
        $keys = $redis->keys('*'); // 获取所有键
        
        //去掉键前缀
        $keys = array_map(function ($key) {
            return str_replace('catchadmin_database_', '', $key);
        }, $keys);

        if ($keys) {
            $res = [
                'code' => 200,
                'msg' => 'success',
                'data' => $keys
            ];
        } else {
            $res = [
                'code' => 400,
                'msg' => 'no keys found',
                'data' => []
            ];
        }
        
        return response()->json($res);
    }
    //删除key
    public function delete_key(Request $request){
        $key = $request->input('key');
        $redis = app('redis');
        $deleted = $redis->del($key);

        if ($deleted) {
            return response()->json([
                'code' => 200,
                'msg' => '删除成功'
            ]);
        } else {
            return response()->json([
                'code' => 500,
                'msg' => '删除失败'
            ]);
        }
    }
    //入列
    public function redis_list(Request $request){
        $k = $request->input('key');
        $v = $request->input('value');
        $redis = app('redis');
        $redis->lpush($k, $v);
        
        //return $redis->rpop('list_test');
        $data = $redis->lrange($k, 0, -1);
        if($data){
            $res =[
                'code' => 200,
                'msg' => 'success',
                'data' => $redis->lrange($k, 0, -1)
            ];
        }else{
            $res =[
                'code' => 500,
                'msg' => 'fail',
                'data' => 'request fail!'
            ];
        }   
        return json_encode($res);
    }

    



    
}